(function(root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], factory);
    } else if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory();
    } else {
        // Browser globals (root is window)
        root.API = factory();
        root.JLEUtil = {
            formatter_dict(value,dictObj){
                for(var i=0;i<dictObj.length;i++){
                    if(value == dictObj[i].enname)
                        return dictObj[i].cnname;
                }
                return value;
            }
        }
    }
}(this, function() {

    const { get, isString, debounce } = _

    const loginInvalidNote = debounce(function() {
        const msg = '登录已失效，请重新登录'

    }, 500)
    /**
     * @description 创建请求实例
     */
    function createService() {
        // 创建一个 axios 实例
        const service = axios.create()
        // 请求拦截
        service.interceptors.request.use(
            config => config,
            error => {
                // 发送失败
                console.log(error)
                return Promise.reject(error)
            }
        )
        // 响应拦截
        service.interceptors.response.use(
            response => {
                // dataAxios 是 axios 返回数据中的 data
                const dataAxios = response.data
                // 这个状态码是和后端约定的
                const {
                    code
                } = dataAxios
                // 根据 code 进行判断
                if (typeof dataAxios == "string" && dataAxios.indexOf('登录已失效') != -1) {
                    // 登陆失效 
                    loginInvalidNote()
                } else if (typeof dataAxios == "string" && dataAxios.trim().indexOf('MSG_CDE') != -1) {
                    const errorMsg = dataAxios.trim()
                    const match = errorMsg.match(/\[MSG_CDE (\w+)/i)
                    return Promise.reject({
                        "MSG_CDE": match[1]
                    })
                } else if (
                    response.config.headers["download-file"] == "download" ||
                    response.headers["content-type"] == "application/msexcel"
                ) {
                    // 下载文件
                    return response
                } else if (code === undefined) {
                    // 如果没有 code 代表这不是项目后端开发的接口 比如可能是 D2Admin 请求最新版本
                    if (isString(dataAxios)) {
                        try {
                            return eval(`(${dataAxios})`)
                        } catch (e) {
                            return dataAxios
                        }
                    } else {
                        return dataAxios
                    }
                } else {
                    // 有 code 代表这是一个后端接口 可以进行进一步的判断
                    switch (code) {
                        case 0:
                        case '0':
                            // [ 示例 ] code === 0 代表没有错误
                            return dataAxios
                        case 'xxx':
                            // [ 示例 ] 其它和后台约定的 code
                            //errorCreate(`[ code: xxx ] ${dataAxios.msg}: ${response.config.url}`)
                            break
                        default:
                            // 不是正确的 code
                            //errorCreate(`${dataAxios.msg}: ${response.config.url}`)
                            return dataAxios
                    }
                }
            },
            error => {
                const status = get(error, 'response.status')
                switch (status) {
                    case 302: error.message = '登录已失效，请重新登录'; break
                    case 400: error.message = '请求错误'; break
                    case 401: error.message = '未授权，请登录'; break
                    case 403: error.message = '拒绝访问'; break
                    case 404: error.message = `请求地址出错: ${error.response.config.url}`; break
                    case 408: error.message = '请求超时'; break
                    case 500: error.message = '服务器内部错误'; break
                    case 501: error.message = '服务未实现'; break
                    case 502: error.message = '网关错误'; break
                    case 503: error.message = '服务不可用'; break
                    case 504: error.message = '网关超时'; break
                    case 505: error.message = 'HTTP版本不受支持'; break
                    default: break
                }
                console.error(error)
                loginInvalidNote()
                if (status == 401 || status == 302) {
                    let targetWindow = window
                    if (window.parent) {
                        targetWindow = window.parent
                    }
                    targetWindow.location.href = error.config.baseURL + 'login.html'; 
                }
                return Promise.reject(error)
            }
        )
        return service
    }

    /**
     * @description 创建请求方法
     * @param {Object} service axios 实例
     */
    function createRequestFunction(service) {
        return function(config) {
            const configDefault = {
                headers: {
                    // 'Content-Type': get(config, 'headers.Content-Type', 'application/json; charset=UTF-8')
                    'Content-Type': 
                        get(config, 'headers.Content-Type') 
                        || config.dataType == 'form' 
                        && get(config, 'headers.Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
                        || 'application/json; charset=UTF-8'
                },
                maxRedirects: 0,
                timeout: 0,
                baseURL: config.baseURL,
                data: null
            }
            return service(Object.assign(configDefault, config))
        }
    }
    const service = createService()
    return {
        service: service,
        request: createRequestFunction(service),
        
    };
}));